
/**
 * 复选 翻页记住
 */
import mixinViewModule from '@/mixins/view-module'
export default {
  mixins: [mixinViewModule],
  methods: {
    init () {
      this.visible = true
      // 初始化 dataForm
      this.dataForm = {
        ...this.dataForm,
        ...this.initDataForm
      }
      this.page = 1
      this.$nextTick(() => {
        this.getDataList().then(() => {
          this.setDefault()
        })
      })
    },
    // 初始化默认值 从数据库中重新读取
    setDefault () {
      if (Array.isArray(this.defaultValues)) {
        this.dataListSelections = this.defaultValues
        this.refreshCheck()
      } else if (this.defaultValues) {
        this.$http.get(this.mixinViewModuleOptions.getDataListURL, { params: { ids: this.defaultValues, limit: -1 } })
          .then(({ data: res }) => {
            this.dataListSelections = res.data.list
            this.refreshCheck()
          })
      } else {
        this.dataListSelections = []
        this.refreshCheck()
      }
    },
    // 点选
    selectionChangeHandle ({ row, checked }) {
      if (!this.multiple) {
        this.dataListSelections = [row]
        this.refreshCheck()
      } else {
        let index = this.getIndex(this.dataListSelections, row)
        if (checked) {
          if (index === -1) {
            this.dataListSelections = this.dataListSelections.concat(row)
          }
        } else {
          if (index !== -1) {
            this.dataListSelections.splice(index, 1)
          }
        }
      }
    },
    // 获取row所在行号
    getIndex (dataList, row) {
      let ids = dataList.map(c => {
        return c[this.rowIdField]
      })
      return ids.indexOf(row[this.rowIdField])
    },
    // 取交集
    getIntersection (d1, d2) {
      let arr = []
      for (const item1 of d1) {
        if (this.getIndex(d2, item1) !== -1) {
          arr.push(item1)
        }
      }
      return arr
    },
    // 翻页、改变行数、初始化时 刷新选择
    refreshCheck () {
      this.$refs.table1.clearCheckboxRow()
      let arr = this.getIntersection(this.dataList, this.dataListSelections)
      this.$refs.table1.setCheckboxRow(arr, true)
    },
    // 分页, 当前页
    pageCurrentChangeHandle (val) {
      this.page = val
      this.getDataList().then(() => {
        this.refreshCheck()
      })
    },
    // 单个tag清除
    handleClose (tag) {
      this.$refs.table1.toggleCheckboxRow(tag)
      this.selectionChangeHandle({ row: tag, checked: false })
    },
    // 确定
    HandleBackFun () {
      this.$emit('backFun', this.dataListSelections)
      this.visible = false
    },
    // 清除
    handleClear () {
      this.dataListSelections = []
      this.HandleBackFun()
    },
    cellDblclick ({ row }) {
      if (!this.multiple) {
        this.selectionChangeHandle({ row: row, checked: true })
        this.HandleBackFun()
      }
    }
  }
}
